<?php
/**
 * User: YL
 * Date: 2019/6/10
 */

namespace restful\utils;

use restful\traits\InstanceTrait;

class RedisLock
{
    use InstanceTrait;

    protected $connect;

    // 锁定时间(5m)
    protected $lockTime = 300;

    private function __construct()
    {
        $this->connect = Redis::getInstance()->getConnect();
    }

    /**
     * 加锁
     * @param string $key
     * @return bool
     */
    public function lock(string $key)
    {
        return !! $this->connect->executeRaw([
            'SET', $this->getCacheKey($key), 1, 'EX', $this->lockTime, 'NX',
        ]);
    }

    /**
     * 删除锁
     * @param string $key
     * @return bool
     */
    public function unlock(string $key)
    {
        return !! $this->connect->del([$this->getLockKey($key)]);
    }

    /**
     * 获取缓存key
     * @param string $key
     * @return string
     */
    protected function getCacheKey(string $key)
    {
        return Redis::getInstance()->getPrefix() . $this->getLockKey($key);
    }

    /**
     * 获取加锁的key
     * @param string $key
     * @return string
     */
    protected function getLockKey(string $key)
    {
        return 'lock:' . $key;
    }
}